<!DOCTYPE HTML>
<html>
<head>
    <!-- twitter bootstrap CSS stylesheet - included to make things pretty, not needed or used by cornerstone -->
    <link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">

        <h1>
            changeimage/index.html
        </h1>

        This is an example of changing the image displayed in an element.  This could be used
        to show different key images or a stack of images (e.g. MRI series).  Use the mouse wheel
        to change between images or press the buttons below.

        <br>
        <br>

        <div id="dicomImage" style="width:512px;height:512px"
            oncontextmenu="return false"
            onmousedown="return false">
        </div>

        <button id="imageButton1" type="button" class="btn btn-default">Image #1</button>
        <button id="imageButton2" type="button" class="btn btn-default">Image #2</button>

    </div>
</body>

<!-- include the cornerstone library -->
<script src="../../dist/cornerstone.js"></script>
<script>window.cornerstone || document.write('<script src="https://unpkg.com/cornerstone-core">\x3C/script>')</script>

<!-- include special code for these examples which provides images -->
<script src="../exampleImageIdLoader.js"></script>

<script>
    const element = document.getElementById('dicomImage');
    cornerstone.enable(element);

    const imageIds = [
        'example://1',
        'example://2'
    ];

    let currentImageIndex = 0;

    // show image #1 initially
    function updateTheImage(imageIndex) {
        currentImageIndex = imageIndex;
        cornerstone.loadImage(imageIds[currentImageIndex]).then(function(image) {
            cornerstone.displayImage(element, image);
        });
    }

    updateTheImage(0);

    // Add event handlers to change images
    document.getElementById('imageButton1').addEventListener('click', function (e) {
        updateTheImage(0);
    });

    document.getElementById('imageButton2').addEventListener('click', function (e) {
        updateTheImage(1);
    });

    const wheelEvents = ['mousewheel', 'DOMMouseScroll'];

    wheelEvents.forEach((eventType) => {
      element.addEventListener(eventType, function (e) {
        // Firefox e.detail > 0 scroll back, < 0 scroll forward
        // chrome/safari e.wheelDelta < 0 scroll back, > 0 scroll forward
        if (e.wheelDelta < 0 || e.detail > 0) {
          if (currentImageIndex === 0) {
            updateTheImage(1);
          }
        } else {
          if (currentImageIndex === 1) {
            updateTheImage(0);
          }
        }

        // Prevent page fom scrolling
        return false;
      });
    });
</script>
</html>
